import {_decorator, Component, Node, Collider, ICollisionEvent} from 'cc';
import {MonsterBulletViewModel} from "db://assets/Scripts/MVC/Monster/Bullet/MonsterBulletViewModel";
import {MonsterBulletUiState} from "db://assets/Scripts/MVC/Monster/Bullet/MonsterBulletUiState";
import {CollisionGroup} from "db://assets/Scripts/Common/CollisionGroup";
import {PoolManager} from "db://assets/Scripts/framework/PoolManager";

const {ccclass, property} = _decorator;

/**
 * 敌机子弹Controller
 */
@ccclass('MonsterBulletController')
export class MonsterBulletController extends Component {
    /**
     * 敌机子弹ViewModel
     */
    public viewModel: MonsterBulletViewModel = new MonsterBulletViewModel();
    /**
     * 敌机子弹UiState
     */
    public uiState: MonsterBulletUiState = this.viewModel.uiState;

    onEnable() {
        // 碰撞检测
        this.node.getComponent(Collider).on('onCollisionEnter', this.onCollisionEnter, this);
    }

    onDisable() {
        // 移除碰撞检测
        this.node.getComponent(Collider).off('onCollisionEnter', this.onCollisionEnter, this);
    }

    start() {

    }

    update(deltaTime: number) {
        // 移动
        this.move(deltaTime);
        // 超范围检测
        this.checkRangeOut();
    }

    /**
     * 移动敌机子弹
     *
     * @param deltaTime 帧间隔时间
     */
    private move(deltaTime: number) {
        // 获取位置
        let position = this.node.position;
        // 设置位置
        this.node.setPosition(position.x, position.y, position.z + this.uiState.speed * deltaTime);
    }

    /**
     * 超范围检测
     */
    private checkRangeOut() {
        // 获取位置
        let position = this.node.position;
        // 当超过销毁阈值时
        if (position.z > this.uiState.rangeOut) {
            // 回收节点
            this.recycle();
        }
    }

    /**
     * 碰撞检测
     */
    private onCollisionEnter(event: ICollisionEvent) {
        // 获取另一个碰撞器分组
        const group = event.otherCollider.getGroup();
        // 与玩家飞机发生碰撞
        if (group === CollisionGroup.PLAYER_PLANE) {
            // 回收节点
            this.recycle();
        }
    }

    /**
     * 回收节点
     */
    private recycle() {
        // 回收节点
        PoolManager.getInstance().putNode(this.node);
        // 重置ViewModel
        this.viewModel.reset();
    }
}